package webapp.mvc.wechat_handlers;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import webapp.mvc.exceptions.UserException;
import webapp.mvc.models.UserEntity;
import webapp.mvc.services.IUserService;

import java.util.Map;

public class WechatSubscribeHandler implements WxMpMessageHandler {
    private static final Logger LOG = LoggerFactory.getLogger(WechatSubscribeHandler.class);

    @Autowired
    private IUserService userService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        String openId = wxMessage.getFromUserName();
        String lang = "zh_CN";
        WxMpUser wxMpUser = wxMpService.userInfo(openId, lang);
        try {
            UserEntity userEntity = userService.createWechatUserBinding(openId, wxMpUser.getNickname(), wxMpUser.getSexId(), null);
            return null;
        } catch (UserException e) {
            LOG.error("create wechat user binding error", e);
            return null;
        }
    }
}
